<?php
/**
 * php模板引擎
 * @link      http://www.imtfy.com
 */
class tpl{
	public $tplurl;
	public $tplstart;
	public $tplend;
	public $tpcachetime;
	public $tpcacheDir;
	public $tptemplateDir;
public function __construct($config){
	$this->tplstart=$config['tplstart'];
	$this->tplend=$config['tplend'];	
	$this->tpcachetime=$config['tplcachetime'];	
	$this->tpcacheDir=$config['tplcacheDir'];	
	$this->tptemplateDir=$config['tpltemplateDir'];
}


//外部获取解析后模板地址
public function geturl($tplName = null,$type = true,$ext=false,$ntpl=2){
	if($ext){
		$tplUrl=$tplName;
		$cachefile=$ext;
	}else{
		//获得文件的名称
		if(M['TemplateType'] == 'file'){
			$Url = is_null($tplName) ? M_PATH.M_C.'_'.M_M.'.html' :($ntpl=='top'? $tplName.'.html':M_PATH.$tplName.'.html');
		}else{
			$Url = is_null($tplName) ? M_PATH.M_C.M['Ds'].M_M.'.html' : ($ntpl=='top'? $tplName.'.html':M_PATH.$tplName.'.html');
		}
		//真实文件地址
		$tplUrl=$this->tptemplateDir.$Url;
		$cachefile=$this->tpcacheDir.$Url;
		if($type){
			//判断缓存时间
			if($this->tpcachetime<0) {return $tplUrl;}
			$cachefiletime=@filemtime($cachefile);
			if(($cachefiletime+$this->tpcachetime)>time()) {
				Return $cachefile;
			}
		}else{
			return $tplUrl;
		}
	}
	//解析模板
	$content=$this->template($tplUrl);
	if($content===false) {
		$content='template not found:'.$tplUrl;
	}
	//生成文件
	if(!is_dir(dirname($cachefile))) {
		$this->createDir(dirname($cachefile));
	}
	
	$setCachefile=file_put_contents($cachefile,$content);
	if($setCachefile) {
		Return $cachefile;
	}else{
		Return $tplUrl;
	}
}
public function createDir($path){
	if (!file_exists($path)){
		$this->createDir(dirname($path));
		if(!@mkdir($path, 0777)) {
			die(dirname($path).' permission denied');
		}
	}
}
public function template($tplUrl){
	$templatecontent=@file_get_contents($tplUrl);
	if($templatecontent===false) {Return false;}
	$system_var=array();
	$system_var[1]=array(
		'sys',
		'upload'
	);
	$system_var[2]=array(
		'imtfy.com',
		'/app/upload/'
	);
	$system_syntax=array();
	$system_syntax[1]=array(
		'else',
		'/if',
		'/loop'
	);
	$system_syntax[2]=array(
		'}else{',
		'}',
		'}'
	);
	if(!defined('TemplateStart')) {define('TemplateStart','{');}
	if(!defined('TemplateEnd')) {define('TemplateEnd','}');}
	preg_match_all('/'.$this->tplstart.'(.*)'.$this->tplend.'/U',$templatecontent,$templist);
	foreach($templist[1] as $key=>$thistemp) {
		$templist[3][$key]=0;
		$thistemp=trim($thistemp);
		foreach($system_var[1] as $system_key=>$thisval) {
			if($thistemp==$thisval) {
				$templist[3][$key]=1;
				$templist[1][$key]='echo(\''.$this->echo_replace($system_var[2][$system_key]).'\');';
			}
		}
		foreach($system_syntax[1] as $system_key=>$thisval) {
			if(!$templist[3][$key] && $thistemp==$thisval) {
				$templist[3][$key]=1;
				$templist[1][$key]=$system_syntax[2][$system_key];
			}
		}
		if(!$templist[3][$key] && substr($thistemp,0,2)=='//') {
			$thisothertemp=substr($thistemp,2);
			$templist[3][$key]=1;
			$templist[1][$key]='';
		}
		if(!$templist[3][$key] && substr($thistemp,0,3)=='if ') {
			$thisothertemp=substr($thistemp,3);
			$templist[3][$key]=1;
			$templist[1][$key]='if('.$thisothertemp.'){';
		}
		if(!$templist[3][$key] && substr($thistemp,0,6)=='class ') {
			$thisothertemp=substr($thistemp,6);
			$templist[3][$key]=1;
			if(stripos($thisothertemp,'.')===false) {
				$thisothertemp.='.php';
			}
			$templist[1][$key]='include_once(\''.M_PATH.'/'.M_MODEL.'/'.$thisothertemp.'\');';
		}
		if(!$templist[3][$key] && substr($thistemp,0,7)=='elseif ') {
			$thisothertemp=substr($thistemp,7);
			$templist[3][$key]=1;
			$templist[1][$key]='}elseif('.$thisothertemp.'){';
		}
		if(!$templist[3][$key] && substr($thistemp,0,5)=='loop ') {
			$thisothertemp=substr($thistemp,5);
			$templist[3][$key]=1;
			$templist[1][$key]='foreach('.$thisothertemp.'){';
		}
		if(!$templist[3][$key] && substr($thistemp,0,5)=='file ') {
			$thisothertemp=substr($thistemp,5);
			$templist[3][$key]=1;
			$reAray=array('',2);
			$reAray=\array_replace($reAray,\explode(',',$thisothertemp));
			$templist[1][$key]='@include \''.$this->geturl($reAray[0],true,false,$reAray[1]).'\';';
		}
		if(!$templist[3][$key]) {
			$thisnewtemp=$this->escape_temp_char($thistemp,1);
			$assignment=explode('=',$thisnewtemp);
			if(count($assignment)>2) {
				$templist[3][$key]=0;
			}elseif(count($assignment)==2) {
				$templist[3][$key]=1;
				$charname=$assignment[0];
				$thisnewtemp=$assignment[1];
				if(substr($assignment[0],0,1)!='$') {
					$templist[3][$key]=0;
					unset($charname);
				}
			}else {
				$templist[3][$key]=1;
				$charname=false;
			}
			if($templist[3][$key]) {
				$this_templist_val='';
				$this_templist_newval='';
				$everyfunction=explode('|',$thisnewtemp);
				foreach($everyfunction as $function_key=>$thisfunction) {
					$thisfunction=trim($thisfunction);
					preg_match_all('/\((.*)\)/U',$thisfunction,$iffunction);
					if(isset($iffunction[1][0])) {
						$iffunction[1][0]=trim($iffunction[1][0]);
						$this_function_temp=explode('(',$thisfunction);
						$this_templist_newval=$this_function_temp[0].'(';
						$this_function_args=explode(',',$iffunction[1][0]);
						$this_function_args_new=array();
						if($function_key>0 && !in_array('this',$this_function_args)) {$this_function_args_new[]='this';}
						if(!empty($iffunction[1][0])) {
							$this_function_args_new=array_merge($this_function_args_new,$this_function_args);
						}
						foreach($this_function_args_new as $args_key=>$val) {
							$val=trim($val);
							if($val=='this') {
								$val=$this_templist_val;
							}else {
								$val=trim($val,'"');
								$val=trim($val,'\'');
								$val=$this->escape_temp_char($val);
								$firstletter=substr($val,0,1);
								if($firstletter=='$') {
								}elseif($firstletter=='`') {
									$val=substr($val,1);
								}else {
									$val=$this->echo_replace($val);
									$val='\''.$val.'\'';
								}
							}
							if(count($this_function_args_new)==($args_key+1)) {
								$this_templist_newval.=$val.')';
							}else {
								$this_templist_newval.=$val.',';
							}
						}
						if(count($this_function_args_new)==0) {
							$this_templist_newval.=')';
						}
						$this_templist_val=$this_templist_newval;
						$this_templist_newval='';
					}else {
						$firstletter=substr($thisfunction,0,1);
						if($firstletter=='$') {
						}elseif($firstletter=='`') {
							$thisfunction=substr($thisfunction,1);
							$thisfunction=$this->escape_temp_char($thisfunction);
						}else {
							$thisfunction=trim($thisfunction,'"');
							$thisfunction=trim($thisfunction,'\'');
							$thisfunction=$this->escape_temp_char($thisfunction);
							$thisfunction=$this->echo_replace($thisfunction);
							$thisfunction='\''.$thisfunction.'\'';
						}
						$this_templist_val=$thisfunction;
					}
				}
			}
			if($templist[3][$key] && $charname) {
				$templist[1][$key]=$charname.'='.$this_templist_val.';';
			}elseif($templist[3][$key]) {
				$templist[1][$key]='echo('.$this_templist_val.');';
			}
			
		}
	}
	foreach($templist[0] as $key=>$val) {
		if($templist[3][$key]) {
			$templatecontent=str_replace($val,'<?php '.$templist[1][$key].' ?>',$templatecontent);
		}
	}
	Return $templatecontent;
		
	}
public function escape_temp_char($str,$encode=0) {
	$array=array();
	$array[1]=array('\\\'','\=','\,','\|','\(','\)','\\`','\array');
	$array[2]=array('--quotes--','--equal--','--comma--','--vertical--','--lbrackets--','--rbrackets--','--topcomma--','--array--');
	$array[3]=array('\'','=',',','|','(',')','','array()');
	foreach($array[1] as $key=>$val) {
		if($encode) {
			$str=str_replace($array[1][$key],$array[2][$key],$str);
		}else {
			$str=str_replace($array[2][$key],$array[3][$key],$str);
		}
	}
	Return $str;
}

public function echo_replace($str) {
	$str=str_replace("'","\\'",$str);
	Return $str;
}


}

?>